package com.ihr360.excel.aggregatemodule.service.impl;

import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.exception.Ihr360SpreadSheetAsynException;
import com.ihr360.commons.lang.StringUtils;
import com.ihr360.commons.vo.ResultInfo;
import com.ihr360.excel.aggregatemodule.service.ExcelAggregateService;
import com.ihr360.excel.aggregatemodule.service.ExcelCloudService;
import com.ihr360.excel.aggregatemodule.service.IrenshiFileDubboService;
import com.ihr360.excel.vo.ImportResult;
import com.ihr360.excel.vo.ProgressContext;
import com.ihr360.excel.vo.ProgressContextFile;
import com.ihr360.excel.vo.ProgressResult;
import com.ihr360.sharedservice.api.DataCacheService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author richey
 */
@Service
public class ExcelAggregateServiceImpl implements ExcelAggregateService {

    Logger logger = LoggerFactory.getLogger(ExcelAggregateServiceImpl.class);


    @Autowired
    private ExcelCloudService excelCloudService;

    @Autowired
    private IrenshiFileDubboService irenshiFileDubboService;

    @Autowired
    private DataCacheService dataCacheService;

    @Override
    @Async
    public void preHandle(ProgressContext progressContext) {

        if (org.apache.commons.lang3.StringUtils.isAnyEmpty(progressContext.getUserId(), progressContext.getCompanyId(), progressContext.getModuleCode())) {
            logger.error("导入失败,参数异常，userId：{}，companyId：{}，moduleCode:{}", progressContext.getUserId(), progressContext.getCompanyId(), progressContext.getModuleCode());
            excelCloudService.saveExcelProcessorJournal(progressContext, "导入失败，参数异常");
            throw new Ihr360SpreadSheetAsynException(progressContext.getProgressKey(), "导入失败，参数异常");
        }

        ProgressContextFile file = progressContext.getFile();
        if (file == null) {
            logger.error("文件处理失败，参数异常，从文件上下文中未取到文件");
            excelCloudService.saveExcelProcessorJournal(progressContext, "文件处理失败，参数异常");
            throw new Ihr360SpreadSheetAsynException(progressContext.getProgressKey(), "文件处理失败，参数异常");
        }

        String fileId = irenshiFileDubboService.saveExcel(progressContext);
        logger.info("上传到文件服务器完成，fileId：" + fileId);

        if (StringUtils.isEmpty(fileId)) {
            logger.error("文件服务器未返回文件Id");
            excelCloudService.saveExcelProcessorJournal(progressContext, "读取文件失败！");
            throw new Ihr360SpreadSheetAsynException(progressContext.getProgressKey(), "读取文件失败！");
        }
        progressContext.setFileId(fileId);

        //模拟第一步失败
//        throw new Ihr360SpreadSheetAsynException(progressContext.getProgressKey(), "模拟第一步失败啦！");


        excelCloudService.handleExcel(progressContext);
    }

    @Override
    public ProgressResult getProgressResult(ProgressContext progressContext) {
        return excelCloudService.getProgressResult(progressContext);
    }

    @Override
    public ImportResult getImportResult(ProgressContext progressContext) {
        return excelCloudService.getImportResult(progressContext);
    }

    @Override
    public ResultInfo interruptProgress(ProgressContext progressContext) {
        return excelCloudService.interruptProgress(progressContext);
    }

    @Override
    public void downloadErrorFile(ProgressContext progressContext, ServletOutputStream outputStream) {

        String errorFileId =  excelCloudService.getErrorFileId(progressContext);

        if (StringUtils.isEmpty(errorFileId)) {
            logger.error("错误文件不存在");
            throw new Ihr360Exception(null, "下载文件失败！");
        }

        ProgressContextFile file = irenshiFileDubboService.getFile(errorFileId, progressContext.getProgressKey());
        try {
            IOUtils.copy(new ByteArrayInputStream(file.getBytes()), outputStream);
            outputStream.flush();
        } catch (IOException e) {
            logger.error(e.toString());
            throw new Ihr360Exception(null, "下载文件失败！");
        }
    }

}
